#include "paintworker.h"
#include "datacenter.h"
#include "ivdspaint.h"
#include <QThread>
#include <QTimer>

class PaintWorkerPrivate : public QObject
{
    Q_OBJECT
public:
    PaintWorkerPrivate();
    ~PaintWorkerPrivate();

    void start(const QString *arg = Q_NULLPTR);
    void stop();

signals:
    void paint(const VdsMeasureDataPtr data);

public slots:
    void onDataReady(const VdsMeasureDataPtr data);
    void onPaintDone();
    void onEnablePaint();

private:
    bool m_enablePaint; // 使能绘制
    const int m_paintInterval; // 最小绘制间隔
    QThread m_thread;
};

PaintWorker::PaintWorker(IVdsPaint *parent) : IComponent("PaintWorker"), d(new PaintWorkerPrivate)
{
    QObject::connect(DataCenter::instance(), &DataCenter::dataFileReady, parent, &IVdsPaint::onDataFileReady);
    QObject::connect(DataCenter::instance(), &DataCenter::measureError, parent, &IVdsPaint::onMeasureError);
    QObject::connect(DataCenter::instance(), &DataCenter::dataReady, d, &PaintWorkerPrivate::onDataReady);
    QObject::connect(d, &PaintWorkerPrivate::paint, parent, &IVdsPaint::onPaintChart);
    QObject::connect(parent, &IVdsPaint::paintDone, d, &PaintWorkerPrivate::onPaintDone);
}

PaintWorker::~PaintWorker()
{
    delete d;
}

void PaintWorker::start(const QString *arg)
{
    d->start(arg);
}

void PaintWorker::stop()
{
    d->stop();
}

void PaintWorkerPrivate::start(const QString *arg)
{
    Q_UNUSED(arg)
    m_enablePaint = true;
    m_thread.start();
}

void PaintWorkerPrivate::stop()
{
    m_thread.quit();
    m_thread.wait();
}

PaintWorkerPrivate::PaintWorkerPrivate() : m_enablePaint(true), m_paintInterval(100)
{
    moveToThread(&m_thread);
}

PaintWorkerPrivate::~PaintWorkerPrivate()
{
    stop();
}

void PaintWorkerPrivate::onEnablePaint()
{
    m_enablePaint = true;
}

void PaintWorkerPrivate::onPaintDone()
{
    QTimer::singleShot(m_paintInterval, this, &PaintWorkerPrivate::onEnablePaint);
}

void PaintWorkerPrivate::onDataReady(const VdsMeasureDataPtr data)
{
    if (m_enablePaint)
    {
        m_enablePaint = false;
        emit paint(data);
    }
}

#include "paintworker.moc"
